import { ElMessage } from 'element-plus'
export const getTime = (time, type = 'date', reg="-") => {
	let temptime = time ? parseInt(time, 10) : null
	let result = '---'
	if (temptime) {
		let tdate = new Date(temptime * 1000)
		let year = tdate.getFullYear()
		let month = (tdate.getMonth() + 1) > 9 ? (tdate.getMonth() + 1) : '0' + (tdate.getMonth() + 1)
		let date = (tdate.getDate()) > 9 ? (tdate.getDate()) : '0' + (tdate.getDate())
		let hour = (tdate.getHours()) > 9 ? (tdate.getHours()) : '0' + (tdate.getHours())
		let minute = (tdate.getMinutes()) > 9 ? (tdate.getMinutes()) : '0' + (tdate.getMinutes())
		let second = (tdate.getSeconds()) > 9 ? (tdate.getSeconds())  : '0' + (tdate.getSeconds())
		result = [year, month, date].join(reg)
		if (type == 'time') {
			result += ' ' + [hour, minute, second].join(':')
		}
		if (type == 'min') {
			result += ' ' + [hour, minute, second].join(':')
		}
	}
	return result
}

export const getTimeYearStr = (time, type = 'date', reg=['年', '月', '日', '时', '分', '秒']) => {
	let temptime = time ? parseInt(time, 10) : null
	let result = '---'
	if (temptime) {
		let tdate = new Date(temptime * 1000)
		let year = tdate.getFullYear()
		let month = (tdate.getMonth() + 1) > 9 ? (tdate.getMonth() + 1) : '0' + (tdate.getMonth() + 1)
		let date = (tdate.getDate()) > 9 ? (tdate.getDate()) : '0' + (tdate.getDate())
		if (type == 'date' || type == 'time') { 
			result = `${year}${reg[0]}${month}${reg[1]}${date}${reg[2]}`
		}
		if(type == 'time') {
			let hour = (tdate.getHours()) > 9 ? (tdate.getHours()) : '0' + (tdate.getHours())
			let minute = (tdate.getMinutes()) > 9 ? (tdate.getMinutes()) : '0' + (tdate.getMinutes())
			let second = (tdate.getSeconds()) > 9 ? (tdate.getSeconds())  : '0' + (tdate.getSeconds())
			result += `${hour}${reg[3]}${minute}${reg[4]}${second}${reg[5]}`
		}
	}
	return result
}


export const getParams = (name) => {
	const url = window.location.search;
	const params = new URLSearchParams(url);
	return params.get(name)
}


export const Message = (message, type="success") => {
	ElMessage({
    showClose: false,
    message: message,
    type: type,
  })
}


export const startCountdown = (duration) => {
	let timer = duration, hours, minutes, seconds;
	hours = parseInt(timer / 3600, 10);
	minutes = parseInt((timer % 3600) / 60, 10);
	seconds = parseInt(timer % 60, 10);

	hours = hours < 10 ? "0" + hours : hours;
	minutes = minutes < 10 ? "0" + minutes : minutes;
	seconds = seconds < 10 ? "0" + seconds : seconds;

	return hours + ":" + minutes + ":" + seconds;

}


export const convertSeconds = (seconds, unit="-") => {
	// 计算小时数
	const hours = Math.floor(seconds / 3600);
	// 计算剩余分钟数（去掉小时数所占的秒数）
	seconds %= 3600;
	const minutes = Math.floor(seconds / 60);
	// 计算剩余的秒数（去掉分钟数所占的秒数）
	const secs = seconds % 60;

	return [hours,minutes,secs].join(unit)
}


export const getURLObject = (url = window.location.href) => {
	const searchIndex = url.lastIndexOf('?');
	const search = url.substring(searchIndex + 1);
	if (searchIndex < 0 || !search || (search && !/=/.test(url))) {
		return {
			errMsg: '当前url参数为空',
			errHref: url
		}
	}
	const params = {};
	search.split("&").forEach((param) => {
		let [key, value] = param.split("=");
		params[decodeURIComponent(key)] = decodeURIComponent(value);
	});
	return params;
}

// 千位符
export const getPrice = () => {
	let list = [1,]
	for (let i = 1; i < 21; i++) {
	  list.push(i * 5)
	}
	for (let i = 3; i < 11; i++) {
	  list.push(i * 50)
	}
	return list.map(item => {
	  return {
		label: item,
		value: item
	  }
	})
  }
  
  
  export const getYearPrice = () => {
	let list = []
	for (let i = 2; i < 11; i++) {
	  list.push(i * 50)
	}
	for (let i = 6; i < 11; i++) {
	  list.push(i * 100)
	}
	for (let i = 2; i < 6; i++) {
	  list.push(i * 1000)
	}
	return list.map(item => {
	  return {
		label: item,
		value: item
	  }
	})
  }

  export const validateEmail = (email) => {
		const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		return regex.test(email);
  }

	//验证手机号码
	export const validatePhone = (data) => {
		const regex = /^1[3-9]\d{9}$/;
		return regex.test(data);
  }


  

  export const isMobile = () => {
    return /Mobi|Android|iPhone|iPad|Windows Phone/i.test(window.navigator.userAgent) || window.innerWidth<=500;
  }

	export const qffn = (str) => {
		let arr = str.toString().split("").reverse();
		// console.log("arr:", arr);
		// [8, 7, 6, 5, 4, 3, 2, 1]     // 876, 543, 21  --->  12, 345, 678
		let st = ""; // 用来接收数据
		arr.forEach((cv, i) => {
			if (i != 0 && i % 3 == 0) {
				st = cv + "," + st;
			} else {
				st = cv + st;
			}
		});
		return st;
	};

  // 计算百分比
	export const calculatePercentage = (value, min=-10, max=10) => {
    // 计算当前值在区间内的比例
    const percentage = ((value - min) / (max - min)) * 100;
    return percentage;
}


export const getDynamicValues = (str) => {
	const regex = /\(([^)]+)\)/g;
	const matches = [];
	let match;
	while ((match = regex.exec(str))!== null) {
			matches.push(match[1]);
	}
	return matches;
}



export const getAge = (birthDate) => {
	const birth = new Date(birthDate);
	const now = new Date();
	let age = now.getFullYear() - birth.getFullYear();
	const monthDiff = now.getMonth() - birth.getMonth();
	if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < birth.getDate())) {
			age--;
	}
	return age;
}


export const getInterviewId = (str="") => {
	return str.split(':')[1]
}

export const copyTextToClipboard = async (text) => {
	try {
    await navigator.clipboard.writeText(text);
    console.log('文本已复制到剪贴板');
  } catch (err) {
    console.error('复制失败: ', err);
  } 
}

